import { ModernBaseService } from './base/ModernBaseService';
import { RPGRepository, PlayerRPGData, SkillCreateConfig, SkillOperationResult, PlayerAttributeDetails, LevelUpResult, PlayerBattleData } from '../repository/RPGRepository';
import { Skill } from '../domain/entities/Skill';
import { Player } from '../domain/entities/Player';
import { SkillUse, ActiveBuff } from "../core/rpg/types";
import { Attribute_base, SkillType } from "../shared/face/enums";
import { RPGError, SkillNotFoundError, InsufficientLevelError } from '../domain/errors/RPGError';
import { DIContainer } from '../infrastructure/di';
import SkillManager from "../core/rpg/skill/SkManager";
import BuffManager from "../core/rpg/skill/BuffManager";

/**
 * 现代化RPG服务类
 * 完全重构的RPG服务，使用Entity和Repository模式
 * 职责：
 * 1. 角色成长管理
 * 2. 技能系统管理
 * 3. 属性计算和战力评估
 * 4. 战斗数据管理
 */
export class ModernRPGService extends ModernBaseService {
    private rpgRepository: RPGRepository;

    constructor(container?: DIContainer) {
        super(container);
        this.rpgRepository = new RPGRepository(container);
    }

    /**
     * 服务初始化
     */
    protected async onInit(): Promise<void> {
        await this.rpgRepository.init();
        this.log('ModernRPGService initialized successfully');
    }

    /**
     * 服务销毁
     */
    protected async onDestroy(): Promise<void> {
        await this.rpgRepository.destroy();
        this.log('ModernRPGService destroyed successfully');
    }

    // ===== 技能管理 =====

    /**
     * 学习技能
     * @param playerId 玩家ID
     * @param skillConfig 技能配置
     * @returns 学习结果
     */
    async learnSkill(playerId: string, skillConfig: SkillCreateConfig): Promise<SkillOperationResult> {
        return this.withPerformanceMonitoring(async () => {
            this.validateRequiredParams({ playerId, skillConfig }, ['playerId', 'skillConfig']);

            // 验证技能是否存在于技能配置中
            const skillTemplate = SkillManager.getSkillById(skillConfig.id);
            if (!skillTemplate) {
                throw new SkillNotFoundError(skillConfig.id);
            }

            // 补充技能配置信息
            const completeConfig: SkillCreateConfig = {
                ...skillConfig,
                name: skillConfig.name || skillTemplate.name,
                description: skillConfig.description || (skillTemplate as any).description || '',
                type: skillConfig.type || skillTemplate.type || 'active',
                maxLevel: skillConfig.maxLevel || (skillTemplate as any).maxLevel || 10
            };

            const result = await this.rpgRepository.addSkillToPlayer(playerId, completeConfig);
            
            if (result.success) {
                await this.onSkillLearned(playerId, completeConfig);
            }

            return result;
        }, 'learnSkill');
    }

    /**
     * 升级技能
     * @param playerId 玩家ID
     * @param skillId 技能ID
     * @returns 升级结果
     */
    async upgradeSkill(playerId: string, skillId: string): Promise<SkillUpgradeResult> {
        return this.withPerformanceMonitoring(async () => {
            this.validateRequiredParams({ playerId, skillId }, ['playerId', 'skillId']);

            const result = await this.rpgRepository.upgradePlayerSkill(playerId, skillId);
            
            if (result.success) {
                await this.onSkillUpgraded(playerId, skillId, result.beforeLevel, result.afterLevel);
            }

            return result;
        }, 'upgradeSkill');
    }

    /**
     * 获取玩家技能列表
     * @param playerId 玩家ID
     * @returns 技能列表
     */
    async getPlayerSkills(playerId: string): Promise<Skill[]> {
        this.validateRequiredParams({ playerId }, ['playerId']);
        return await this.rpgRepository.getPlayerSkills(playerId);
    }

    /**
     * 获取技能详情
     * @param playerId 玩家ID
     * @param skillId 技能ID
     * @returns 技能详情
     */
    async getSkillDetails(playerId: string, skillId: string): Promise<SkillDetails> {
        const skills = await this.getPlayerSkills(playerId);
        const skill = skills.find(s => s.id === skillId);
        
        if (!skill) {
            throw new SkillNotFoundError(skillId);
        }

        const skillTemplate = SkillManager.getSkillById(skillId);
        const upgradeInfo = this.calculateSkillUpgradeInfo(skill);

        return {
            skill,
            template: skillTemplate,
            upgradeInfo,
            effects: this.calculateSkillEffects(skill),
            cooldownInfo: await this.getSkillCooldownInfo(playerId, skillId)
        };
    }

    /**
     * 批量升级技能
     * @param playerId 玩家ID
     * @param skillIds 技能ID列表
     * @returns 批量升级结果
     */
    async batchUpgradeSkills(playerId: string, skillIds: string[]): Promise<BatchSkillUpgradeResult> {
        return this.batchProcess(skillIds, async (skillId, index) => {
            return await this.upgradeSkill(playerId, skillId);
        }, 'batchUpgradeSkills');
    }

    // ===== 属性管理 =====

    /**
     * 获取玩家属性详情
     * @param playerId 玩家ID
     * @returns 属性详情
     */
    async getPlayerAttributes(playerId: string): Promise<PlayerAttributeDetails> {
        this.validateRequiredParams({ playerId }, ['playerId']);
        return await this.rpgRepository.getPlayerAttributes(playerId);
    }

    /**
     * 更新玩家属性
     * @param playerId 玩家ID
     * @param attributes 属性变更
     * @returns 更新结果
     */
    async updatePlayerAttributes(playerId: string, attributes: Record<string, number>): Promise<{
        success: boolean;
        message: string;
        updatedAttributes: PlayerAttributeDetails;
    }> {
        return this.withPerformanceMonitoring(async () => {
            this.validateRequiredParams({ playerId, attributes }, ['playerId', 'attributes']);

            await this.rpgRepository.updatePlayerAttributes(playerId, attributes);
            const updatedAttributes = await this.rpgRepository.getPlayerAttributes(playerId);

            // 清除相关缓存
            this.clearCache(`player_power_${playerId}`);
            this.clearCache(`battle_data_${playerId}`);

            return {
                success: true,
                message: '属性更新成功',
                updatedAttributes
            };
        }, 'updatePlayerAttributes');
    }

    /**
     * 计算战力
     * @param playerId 玩家ID
     * @returns 战力值
     */
    async calculatePlayerPower(playerId: string): Promise<number> {
        return this.cached(`player_power_${playerId}`, async () => {
            const attributes = await this.getPlayerAttributes(playerId);
            return attributes.powerRating;
        }, 60000); // 缓存1分钟
    }

    /**
     * 比较玩家战力
     * @param playerIds 玩家ID列表
     * @returns 战力排名
     */
    async comparePlayerPower(playerIds: string[]): Promise<PowerRanking[]> {
        const rankings: PowerRanking[] = [];

        for (const playerId of playerIds) {
            try {
                const power = await this.calculatePlayerPower(playerId);
                const attributes = await this.getPlayerAttributes(playerId);
                
                rankings.push({
                    playerId,
                    powerRating: power,
                    level: (await this.rpgRepository.getPlayerRPGData(playerId)).level,
                    mainAttributes: {
                        attack: attributes.totalAttributes[Attribute_base.物理攻击] || 0,
                        magicAttack: attributes.totalAttributes[Attribute_base.魔法攻击] || 0,
                        defense: attributes.totalAttributes[Attribute_base.物理防御] || 0,
                        hp: attributes.totalAttributes[Attribute_base.最大生命值] || 0
                    }
                });
            } catch (error) {
                this.log(`Failed to get power for player ${playerId}: ${(error as any).message}`, 'warn');
            }
        }

        // 按战力排序
        rankings.sort((a, b) => b.powerRating - a.powerRating);
        
        // 添加排名
        rankings.forEach((ranking, index) => {
            ranking.rank = index + 1;
        });

        return rankings;
    }

    // ===== 经验和等级管理 =====

    /**
     * 添加经验值
     * @param playerId 玩家ID
     * @param exp 经验值
     * @param source 经验来源
     * @returns 升级结果
     */
    async addExperience(playerId: string, exp: number, source: string = 'unknown'): Promise<LevelUpResult> {
        return this.withPerformanceMonitoring(async () => {
            this.validateRequiredParams({ playerId, exp }, ['playerId', 'exp']);

            if (exp <= 0) {
                throw new Error('Experience must be positive');
            }

            const result = await this.rpgRepository.addExperience(playerId, exp);
            
            if (result.leveledUp) {
                await this.onPlayerLevelUp(playerId, result.oldLevel, result.newLevel);
            }

            // 记录经验获得日志
            this.log(`Player ${playerId} gained ${exp} exp from ${source}, level: ${result.newLevel}`);

            return result;
        }, 'addExperience');
    }

    /**
     * 获取玩家等级信息
     * @param playerId 玩家ID
     * @returns 等级信息
     */
    async getPlayerLevelInfo(playerId: string): Promise<PlayerLevelInfo> {
        const rpgData = await this.rpgRepository.getPlayerRPGData(playerId);
        const expForNextLevel = this.getExpRequiredForLevel(rpgData.level + 1);
        const expForCurrentLevel = this.getExpRequiredForLevel(rpgData.level);
        
        return {
            currentLevel: rpgData.level,
            currentExp: rpgData.experience,
            expForNextLevel,
            expForCurrentLevel,
            expProgress: rpgData.experience / expForNextLevel,
            expToNextLevel: expForNextLevel - rpgData.experience
        };
    }

    // ===== 战斗相关 =====

    /**
     * 获取玩家战斗数据
     * @param playerId 玩家ID
     * @returns 战斗数据
     */
    async getPlayerBattleData(playerId: string): Promise<PlayerBattleData> {
        return this.cached(`battle_data_${playerId}`, async () => {
            return await this.rpgRepository.getPlayerBattleData(playerId);
        }, 30000); // 缓存30秒
    }

    /**
     * 更新战斗状态
     * @param playerId 玩家ID
     * @param updates 状态更新
     * @returns 更新结果
     */
    async updateBattleState(playerId: string, updates: Partial<PlayerBattleData>): Promise<{
        success: boolean;
        message: string;
        currentState: PlayerBattleData;
    }> {
        return this.withPerformanceMonitoring(async () => {
            await this.rpgRepository.updateBattleState(playerId, updates);
            
            // 清除缓存
            this.clearCache(`battle_data_${playerId}`);
            
            const currentState = await this.getPlayerBattleData(playerId);

            return {
                success: true,
                message: '战斗状态更新成功',
                currentState
            };
        }, 'updateBattleState');
    }

    /**
     * 恢复玩家状态
     * @param playerId 玩家ID
     * @param type 恢复类型
     * @returns 恢复结果
     */
    async restorePlayerState(playerId: string, type: 'hp' | 'mp' | 'all' = 'all'): Promise<{
        success: boolean;
        message: string;
        restoredValues: Record<string, number>;
    }> {
        return this.withPerformanceMonitoring(async () => {
            const battleData = await this.getPlayerBattleData(playerId);
            const updates: Partial<PlayerBattleData> = {};
            const restoredValues: Record<string, number> = {};

            if (type === 'hp' || type === 'all') {
                updates.currentHp = battleData.maxHp;
                restoredValues.hp = battleData.maxHp;
            }

            if (type === 'mp' || type === 'all') {
                updates.currentMp = battleData.maxMp;
                restoredValues.mp = battleData.maxMp;
            }

            await this.rpgRepository.updateBattleState(playerId, updates);
            
            // 清除缓存
            this.clearCache(`battle_data_${playerId}`);

            return {
                success: true,
                message: `${type === 'all' ? '完全' : type.toUpperCase()}恢复成功`,
                restoredValues
            };
        }, 'restorePlayerState');
    }

    /**
     * 获取技能冷却信息
     * @param playerId 玩家ID
     * @param skillId 技能ID
     * @returns 冷却信息
     */
    async getSkillCooldownInfo(playerId: string, skillId: string): Promise<SkillCooldownInfo> {
        // 这里需要与冷却系统集成，暂时返回默认值
        return {
            skillId,
            isOnCooldown: false,
            remainingTime: 0,
            totalCooldown: 0,
            canUse: true
        };
    }

    // ===== 数据统计和分析 =====

    /**
     * 获取玩家RPG统计
     * @param playerId 玩家ID
     * @returns 统计信息
     */
    async getPlayerRPGStats(playerId: string): Promise<PlayerRPGStats> {
        const rpgData = await this.rpgRepository.getPlayerRPGData(playerId);
        const attributes = await this.getPlayerAttributes(playerId);
        const levelInfo = await this.getPlayerLevelInfo(playerId);

        return {
            playerId,
            level: rpgData.level,
            experience: rpgData.experience,
            powerRating: attributes.powerRating,
            skillCount: rpgData.skills.length,
            activeBuffCount: rpgData.buffs.length,
            levelProgress: levelInfo.expProgress,
            attributeDistribution: this.analyzeAttributeDistribution(attributes.totalAttributes),
            skillTypeDistribution: this.analyzeSkillTypes(rpgData.skills),
            lastUpdated: rpgData.lastUpdated
        };
    }

    /**
     * 批量获取多个玩家统计
     * @param playerIds 玩家ID列表
     * @returns 批量统计结果
     */
    async getBatchPlayerStats(playerIds: string[]): Promise<BatchStatsResult> {
        return this.batchProcess(playerIds, async (playerId, index) => {
            return await this.getPlayerRPGStats(playerId);
        }, 'getBatchPlayerStats');
    }

    // ===== 私有辅助方法 =====

    /**
     * 计算技能升级信息
     */
    private calculateSkillUpgradeInfo(skill: Skill): SkillUpgradeInfo {
        const canUpgrade = skill.level < skill.maxLevel;
        const upgradeCost = this.calculateSkillUpgradeCost(skill);
        
        return {
            canUpgrade,
            currentLevel: skill.level,
            maxLevel: skill.maxLevel,
            upgradeCost,
            nextLevelEffects: canUpgrade ? this.getNextLevelEffects(skill) : null
        };
    }

    /**
     * 计算技能效果
     */
    private calculateSkillEffects(skill: Skill): SkillEffects {
        // 这里需要与技能效果系统集成
        return {
            damage: 0,
            healing: 0,
            buffEffects: [],
            specialEffects: []
        };
    }

    /**
     * 计算技能升级成本
     */
    private calculateSkillUpgradeCost(skill: Skill): SkillUpgradeCost {
        const baseCost = 100;
        const levelMultiplier = Math.pow(1.5, skill.level);
        
        return {
            gold: Math.floor(baseCost * levelMultiplier),
            materials: [],
            requirements: []
        };
    }

    /**
     * 获取下一级效果
     */
    private getNextLevelEffects(skill: Skill): any {
        // 这里需要根据技能系统实现
        return {
            damageIncrease: 10,
            cooldownReduction: 1
        };
    }

    /**
     * 获取升级所需经验
     */
    private getExpRequiredForLevel(level: number): number {
        return level * 100; // 简单的经验公式
    }

    /**
     * 分析属性分布
     */
    private analyzeAttributeDistribution(attributes: Record<string, number>): AttributeDistribution {
        const total = Object.values(attributes).reduce((sum, value) => sum + value, 0);
        const distribution: AttributeDistribution = {};

        for (const [attr, value] of Object.entries(attributes)) {
            distribution[attr] = {
                value,
                percentage: total > 0 ? (value / total) * 100 : 0
            };
        }

        return distribution;
    }

    /**
     * 分析技能类型分布
     */
    private analyzeSkillTypes(skills: Skill[]): SkillTypeDistribution {
        const distribution: SkillTypeDistribution = {};
        
        skills.forEach(skill => {
            const type = skill.type;
            if (!distribution[type]) {
                distribution[type] = { count: 0, skills: [] };
            }
            distribution[type].count++;
            distribution[type].skills.push(skill.id);
        });

        return distribution;
    }

    // ===== 事件处理 =====

    /**
     * 技能学习事件处理
     */
    private async onSkillLearned(playerId: string, skillConfig: SkillCreateConfig): Promise<void> {
        this.log(`Player ${playerId} learned skill: ${skillConfig.name}`);
        
        // 清除相关缓存
        this.clearCache(`player_power_${playerId}`);
        this.clearCache(`battle_data_${playerId}`);
        
        // 可以在这里添加任务进度更新等逻辑
        // await this.updateTaskProgress(playerId, 'LEARN_SKILL', 1);
    }

    /**
     * 技能升级事件处理
     */
    private async onSkillUpgraded(playerId: string, skillId: string, beforeLevel: number, afterLevel: number): Promise<void> {
        this.log(`Player ${playerId} upgraded skill ${skillId}: ${beforeLevel} -> ${afterLevel}`);
        
        // 清除相关缓存
        this.clearCache(`player_power_${playerId}`);
        this.clearCache(`battle_data_${playerId}`);
    }

    /**
     * 玩家升级事件处理
     */
    private async onPlayerLevelUp(playerId: string, oldLevel: number, newLevel: number): Promise<void> {
        this.log(`Player ${playerId} leveled up: ${oldLevel} -> ${newLevel}`);
        
        // 清除相关缓存
        this.clearCache(`player_power_${playerId}`);
        this.clearCache(`battle_data_${playerId}`);
        
        // 可以在这里添加升级奖励逻辑
        // await this.grantLevelUpRewards(playerId, newLevel);
    }
}

// ===== 接口定义 =====

import { SkillUpgradeResult } from '../repository/RPGRepository';

/**
 * 技能详情接口
 */
export interface SkillDetails {
    skill: Skill;
    template: any;
    upgradeInfo: SkillUpgradeInfo;
    effects: SkillEffects;
    cooldownInfo: SkillCooldownInfo;
}

/**
 * 技能升级信息接口
 */
export interface SkillUpgradeInfo {
    canUpgrade: boolean;
    currentLevel: number;
    maxLevel: number;
    upgradeCost: SkillUpgradeCost;
    nextLevelEffects: any;
}

/**
 * 技能升级成本接口
 */
export interface SkillUpgradeCost {
    gold: number;
    materials: any[];
    requirements: any[];
}

/**
 * 技能效果接口
 */
export interface SkillEffects {
    damage: number;
    healing: number;
    buffEffects: any[];
    specialEffects: any[];
}

/**
 * 技能冷却信息接口
 */
export interface SkillCooldownInfo {
    skillId: string;
    isOnCooldown: boolean;
    remainingTime: number;
    totalCooldown: number;
    canUse: boolean;
}

/**
 * 战力排名接口
 */
export interface PowerRanking {
    playerId: string;
    rank?: number;
    powerRating: number;
    level: number;
    mainAttributes: {
        attack: number;
        magicAttack: number;
        defense: number;
        hp: number;
    };
}

/**
 * 玩家等级信息接口
 */
export interface PlayerLevelInfo {
    currentLevel: number;
    currentExp: number;
    expForNextLevel: number;
    expForCurrentLevel: number;
    expProgress: number;
    expToNextLevel: number;
}

/**
 * 玩家RPG统计接口
 */
export interface PlayerRPGStats {
    playerId: string;
    level: number;
    experience: number;
    powerRating: number;
    skillCount: number;
    activeBuffCount: number;
    levelProgress: number;
    attributeDistribution: AttributeDistribution;
    skillTypeDistribution: SkillTypeDistribution;
    lastUpdated: Date;
}

/**
 * 属性分布接口
 */
export interface AttributeDistribution {
    [attribute: string]: {
        value: number;
        percentage: number;
    };
}

/**
 * 技能类型分布接口
 */
export interface SkillTypeDistribution {
    [skillType: string]: {
        count: number;
        skills: string[];
    };
}

/**
 * 批量技能升级结果接口
 */
export interface BatchSkillUpgradeResult {
    success: boolean;
    results: SkillUpgradeResult[];
    errors: { index: number; item: string; error: string }[];
}

/**
 * 批量统计结果接口
 */
export interface BatchStatsResult {
    success: boolean;
    results: PlayerRPGStats[];
    errors: { index: number; item: string; error: string }[];
}
